#!/usr/bin/evn python
# examples/proxyserv_v2.py

try:
    import httpmessage
except ImportError:
    import sys
    from os.path import dirname, abspath, join
    sys.path.append(abspath(join(dirname(__file__), '..')))

from SocketServer import TCPServer, StreamRequestHandler, ThreadingMixIn
from httpmessage import HttpMessage
import httpmessage.dispatch as dispatch

class ThreadingProxyServer(ThreadingMixIn, TCPServer):
    allow_reuse_address = True
    daemon_threads = True

class ProxyHandlerV2(StreamRequestHandler):

    """Buffers entire request before sending it to server. Returns response
    bytes to client as they are received."""

    def recv_rawdata(self, signal, sender, raw_data):
        assert signal == dispatch.signal.RAW_DATA
        try:
            self.connection.send(raw_data)
        except Exception, e:
            print 'failed to send data because %r' % e
            return dispatch.response.ABORT
        print 'recv [%i] bytes' % len(raw_data)

    def handle(self):
        request = HttpMessage(socket=self.connection)
        response = request.fetch_response()
        response.connection = 'close'
        recv_fn = self.recv_rawdata
        dispatch.connect(
                recv_fn, dispatch.signal.RAW_DATA, response
            )
        self.connection.send(response.str_head())
        response.buffer_all()
        dispatch.disconnect(recv_fn)



if __name__ == "__main__":
    server_address = ('', 8000)
    proxyserver = ThreadingProxyServer(server_address, ProxyHandlerV2)
    print 'proxy serving on %r' % (server_address,)
    try:
        proxyserver.serve_forever()
    except KeyboardInterrupt:
        print '\nexiting...'

